import globalData from "@/globalData";

export default {
  data() {
    return {
      form: {
        subject: "", //工作主题
        taskNum: "", //任务编号
        details: "", //需求描述
        budget: "", //项目预算
        paymentType: "", //付款方式
        deadline: "", //截止日期
        keywords: "", //关键字
        serviceRate: "0.3", //服务费率
        serviceFee: "", //服务费=30%保证金
        cashPledge: "", //保证金=10%项目预算
        orderId: "", //订单编号
        createUser: "", //创建人
        nickName: "", //创建人昵称
        imageUrl: "", //创建人头像
      },
      ImageFiles: [],
      rules: {
        subject: [
          {
            required: true,
            message: "请填写需求名称",
            trigger: ["change", "blur"],
          },
        ],
        paymentType: [
          {
            required: true,
            message: "请选择付款方式",
            trigger: ["change", "blur"],
          },
        ],
        deadline: [
          {
            required: true,
            message: "报名截止日期必须大于当前日期",
            validator: (rule, value, callback) => {
              let date = new Date(value);
              let now = new Date();
              return date.getTime() >= now.getTime();
            },
            trigger: ["change", "blur"],
          },
        ],
        keywords: [
          {
            required: true,
            message: "请添加关键字",
            validator: (rule, value, callback) => {
              return value.length != 0;
            },
            trigger: ["change", "blur"],
          },
        ],
        details: [
          {
            required: true,
            message: "请填写需求描述",
            trigger: ["change", "blur"],
          },
        ],
      },
      paymentList: [
        {
          value: "全额付款",
          label: "全额付款",
        },
        {
          value: "分期付款3:3:3:1",
          label: "分期付款3:3:3:1",
        },
        {
          value: "分期付款1:3:3:3",
          label: "分期付款1:3:3:3",
        },
        {
          value: "分期付款1:3:6",
          label: "分期付款1:3:6",
        },
        {
          value: "分期付款3:7",
          label: "分期付款3:7",
        },
        {
          value: "分期付款5:5",
          label: "分期付款5:5",
        },
      ],
      timeParams: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
      },
      showItem: false,
      disable: false,
      paymentShow: false,
      deadlineShow: false,
      deliveryShow: false,
      userId: "",
      modal_show: false,
      clickModal: 0,
      ResumeFiles: [],
      taskNumber: "",
      PrivilegedStatus: "", // 是否为支付特权人员。yes:是；no:否。默认：no
      chooseTypes: [
        {
          text: "全额付款",
          action: "fullPayment",
        },
        {
          text: "0元支付",
          action: "payALittle",
        },
        {
          text: "取消",
          action: "closePopup",
        },
      ],
    };
  },
  // 每次进入页面时，获取附件
  onShow() {
    this.getFiles(this.form.taskNum);
  },

  async onLoad() {
    //未登录跳转到登录页面
    this.checkLogin();
    this.taskNumber = this.$query.taskNumber;
    if (this.taskNumber) {
      await this.getJobDetail();
    }
    // 保存选中的标签列表
    uni.$on("saveTagList", (tagList = []) => {
      this.form.keywords = tagList;
    });
    await this.getServiceRate();
    this.form.createUser = uni.getStorageSync("userInfo").userId;
    await this.autoDocNumber();
    await this.getPrivilegedStatus();
  },

  mounted() {},

  onUnload() {
    uni.$off("saveTagList");
  },

  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },

  methods: {
    //获取服务费率
    async getServiceRate() {
      this.form.ServiceRate = "0.3";
    },
    //服务费提示
    showTips(action) {
      if (action) {
        this.modal_show = true;
      }
      if (this.clickModal === 0) {
        this.modal_show = true;
      }
      this.clickModal++;
    },

    toTagSettingPage(prevPageIsSelectList = [], mode = 4) {
      uni.setStorageSync("create", prevPageIsSelectList);
      this.$u.route(
        `/pages_private_scene1/ExpertCooperate/common/tag?mode=${mode}`
      );
    },
    async getJobDetail() {
      let result = await this.$u.api.unifyMiniRestGet({
        systemid: "meily",
        url: "/expert/job/" + this.taskNumber,
        loading: true, // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if (result.code === "200" && result.data) {
        this.form = result.data;
        this.form.keywords = this.RestructuringLabel(result.data.keywords);
        this.form.jobId = "";
      } else {
        this.$u.toast(result.msg);
      }
    },
    /**
     * 选择支付的方式
     */
    async clickPopup(item) {
      if (item.action == "closePopup") {
        this.showItem = false;
      } else {
        await this.submitStep2(item.action);
      }
    },
    /**
     * 关闭 选择支付的方式
     */
    closePopup() {
      this.showItem = false;
    },
    /**
     * 根据userid获取支付特权状态
     */
    async getPrivilegedStatus() {
      const userInfo = uni.getStorageSync("userInfo");
      let result = await this.$u.api.unifyMiniRestGet({
        systemid: "meily",
        url: "/user/canQuickPay/" + userInfo.userId,
        loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if (result.code == 200) {
        this.PrivilegedStatus = result.data;
      }
    },
    async submitStep1() {
      if (this.PrivilegedStatus == "yes") {
        this.showItem = true; // 选择支付额度
      } else {
        // 全额付款
        await this.submitStep2("fullPayment");
      }
    },
    /**
     * 提交表单
     */
    async submitStep2(action) {
      let valid = await this.$refs.uForm.validate();
      // 验证通过
      if (valid) {
        //未登录跳转到登录页面
        this.checkLogin();
        this.form.budget >= 100
          ? await this.goToPay(action)
          : this.$u.toast("项目预算不能低于100元！");
      }
    },
    async goToPay(action) {
      this.disable = true;
      uni.showLoading({ mask: true });
      const userInfo = uni.getStorageSync("userInfo");
      //1、定义商品信息
      let goodsInfo = { goodsNum: 1, goodsWeight: 0 };
      //2、定义商户信息
      let mchInfo = {
        mchname: userInfo.nickName,
        mchimage: userInfo.avatarUrl,
      };
      //3、计算保证金，项目预算的10%
      //转化成分需要乘以100，这里抵消了10%，所以是乘以10
      this.form.cashPledge = this.accMul(this.form.budget, "10");
      //4、计算服务费，项目款的3%
      this.form.serviceFee = this.accMul(this.form.budget, "0.03");
      //5、计算支付金额,项目款+服务费
      const budget = parseFloat(this.form.budget);
      const serviceFee = parseFloat(this.form.serviceFee);
      let payPrice = budget + serviceFee;
      payPrice = this.accMul(payPrice, "100");
      if (action == "payALittle") {
        payPrice = 0;
      }

      //5、订单信息
      let orderObj = {
        userid: userInfo.userId,
        openid: userInfo.openid,
        tradeDesc: this.form.subject + "-(项目款)",
        payPrice: payPrice,
        productID: this.form.taskNum,
        goodsInfo: goodsInfo,
        mchInfo: mchInfo,
        remark: this.form.subject + "-(项目款)",
      };
      //6、获取授权信息
      let authInfo = await this.geAuthInfo(orderObj);
      if (authInfo.code != 200) {
        this.showMSG("error", "支付失败！");
        this.disable = false;
        return;
      }
      //7、请求微信支付接口
      let wxPayUrl = "/api/unifiedorder";
      let rep = await this.postWxpayServer(wxPayUrl, orderObj, authInfo);
      if (rep.code != 200) {
        this.showMSG("error", "支付失败！");
        this.disable = false;
        return;
      }
      this.form.orderId = rep.data.tradeNo;
      //8、调用微信支付
      let payRes = rep.data;
      if (!payRes.hasNext) {
        this.publishJob().then((res) => {
          uni.redirectTo({
            url:
              "/pages_private_scene1/ExpertCooperate/common/result?mode=1&docUnid=" +
              this.form.taskNum,
          });
        });
        return;
      }
      wx.requestPayment({
        ...payRes,
        success: (res) => {
          console.log("支付成功:{}", res);
        },
        fail: (err) => {
          this.disable = false;
        },
        complete: (res) => {
          setTimeout(() => {
            this.doQueryWxPayOk();
          }, 1500);
        },
      });
    },
    accMul(a, b) {
      let getMul = (num) =>
        num.toString().indexOf(".") == -1
          ? 0
          : num.toString().split(".")[1].length;
      let mathpow = (a) => a * 10 ** getMul(a);
      return (mathpow(a) * mathpow(b)) / 10 ** (getMul(a) + getMul(b));
    },
    async doQueryWxPayOk() {
      const userInfo = uni.getStorageSync("userInfo");
      let authObj = {
        userid: userInfo.userId,
        openid: userInfo.openid,
        tradeNo: this.form.orderId,
      };
      let authInfo = await this.geAuthInfo(authObj);
      if (authInfo.code != 200) {
        this.showMSG("error", "支付失败！");
        this.disable = false;
        return;
      }
      let queryStatusUrl = "api/queryorderok";
      let rep = await this.postWxpayServer(queryStatusUrl, authObj, authInfo);
      if (rep.code != 200) {
        this.showMSG("error", "支付失败！");
        this.disable = false;
        return;
      }
      this.publishJob().then((res) => {
        if (res.code == 200) {
          uni.redirectTo({
            url:
              "/pages_private_scene1/ExpertCooperate/common/result?mode=1&docUnid=" +
              this.form.taskNum,
          });
        } else {
          this.showMSG("error", res.msg);
        }
      });
    },
    //请求提交流程接口
    async publishJob() {
      const userInfo = uni.getStorageSync("userInfo");
      //发布专家协作任务
      this.form.createUser = userInfo.userId;
      this.form.nickName = userInfo.nickName;
      this.form.cashPledge = this.accMul(this.form.cashPledge, "0.01");
      this.form.keywords = this.ParseLabel(this.form.keywords);
      let params = this.form;
      params.systemid = "meily";
      params.url = "/expert/job/publish/user";
      params.loading = true;
      await this.$u.api.unifyMiniRest(params);
    },

    /**
     * 移除标签
     */
    onCloseTag(index) {
      this.form.keywords.splice(index, 1);
    },

    /**
     * 接收上传组件传过来的值并更新附件列表数据
     */
    async getData(res) {
      this.ResumeFiles = res;
    },
    /**
     * 初始化附件列表
     * @param {Object} orunid 实例id
     */
    async getFiles(orunid) {
      if (orunid) {
        const userInfo = uni.getStorageSync("userInfo");
        let result = await this.$u.api.unifyRequest({
          userId: userInfo.userId,
          nickName: userInfo.nickName,
          appid: "FILE",
          wf_num: "R_FILE_BL002",
          orunid: orunid,
          fieldName: userInfo.userId,
          loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
        });
        if (result.code == 200) {
          this.ResumeFiles = result.data;
        }
      }
    },
    /**
     * 接收上传组件传过来的值并更新附件列表数据
     * 获取附件列表
     */
    async getImageFiles(res) {
      this.ImageFiles = res;
      let images = ''
      for(let i in this.ImageFiles){
        if(images != ''){
          images += "," + this.ImageFiles[i].url
        }else{
          images = this.ImageFiles[i].url
        }
      }
      this.form.imageUrl = images
    },

    async autoDocNumber() {
      let result = await this.$u.api.unifyMiniRestGet({
        systemid: "meily",
        url: "/expert/job/generate/taskNo",
        loading: true, // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if (result.code == 200) {
        this.form.taskNum = result.data;
      }
    },
  },
};
